﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ShareMarking.Interface;
using ShareMarking.Service;
using System.Configuration;
using System.Data;
using MySoft.Data;
using ComLib;

namespace ShareMarking.Synchronization
{
    class Program
    {
        static void Main(string[] args)
        {
            ComLib.LogLib.Log4NetBase.Log("开始同步数据！");
            string httpstr = ConfigurationManager.AppSettings["nchttp"];
            string access_key_id = ConfigurationManager.AppSettings["access_key_id"];
            string access_key_secret = ConfigurationManager.AppSettings["access_key_secret"];
            var ncsync = new NC_Sync(httpstr, access_key_id, access_key_secret);

            try
            {
                #region 同步NC数据
                Sync(ncsync);
                #endregion

                #region 检测有异常NC处理（isneedupdate=1）
                String sql = String.Format(@"SELECT  * FROM [meadjohnson].[dbo].[nc_ncuser] 
                                              a where a.[state] = '活跃员工' AND a.[password]!='' AND a.[name]!='' 
                                              and not EXISTS ( 
                                               SELECT * FROM [meadjohnson].[dbo].[qr_QrCodeRelate] b where b.[rel_Code] = a.[nc_code] and b.[IsDelete] = 0
                                              )");
                DataTable dt = nc_ncuserService.Instance.db.FromSql(sql).ToTable();
                if (dt.Rows.Count > 0)
                {
                    ComLib.LogLib.Log4NetBase.Log("00、==========================检测异常NC有" + dt.Rows.Count + "条");
                    #region 循环添加数据
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        String sql2 = String.Format(@"UPDATE nc_ncuser SET isneedupdate=1 WHERE nc_code='{0}'", dt.Rows[i]["nc_code"].ToString());
                        var result = DbSession.Default.FromSql(sql2).ToScalar();
                        ComLib.LogLib.Log4NetBase.Log("01、==========================处理第" + i + "条异常NCCODE:====NCCODE:" + dt.Rows[i]["nc_code"].ToString() +
                                         "====把旧状态:" + dt.Rows[i]["isneedupdate"].ToString() + "设置为新的状态为:true");
                    }
                    #endregion
                }
                #endregion

                #region 更新NC二维码
                ComLib.LogLib.Log4NetBase.Log("3、==========================更新NC二维码========开始====");
                string vigohttp = ConfigurationManager.AppSettings["vigohttp"];
                string signscrect = ConfigurationManager.AppSettings["signscrect"];
                NC_QRCode ncqrsync = new NC_QRCode(vigohttp, signscrect);
                ncqrsync.Sync_QrCode();
                ComLib.LogLib.Log4NetBase.Log("3、==========================更新NC二维码========结束====");
                #endregion

            }
            catch (Exception ex)
            {
                ComLib.LogLib.Log4NetBase.Log("0-0、====同步NC数据====错误=====" + ex.Message + ex.StackTrace);
            }
        }

        //正式方法
        private static void Sync(NC_Sync ncsync)
        {
            #region 正常请求NC平台数据处理处理
            //先获取所有NC数量
            var count = ncsync.GetNCCount();
            ComLib.LogLib.Log4NetBase.Log("1、====同步NC数据====获取NC数量为：：" + count);

            //设置50页一次
            var pagesize = 50;
            var currentpage = 1;
            var nextpage = 1;
            int a = 0;
            var pagecout = (int)(count / pagesize);
            for (int i = 0; i <= pagecout; i++)
            {
                //获取一页数据
                var resultentity = ncsync.GetNC(currentpage, nextpage, pagesize, count);
                ComLib.LogLib.Log4NetBase.Log("2、====同步NC数据====获取第++" + i + "++页数据：：state:"
                            + resultentity.state + ":::msg:::" + resultentity.message);

                var enlit = resultentity.result.list;
                enlit.ForEach(o =>
                {
                    try
                    {
                        #region 处理一条数据
                        if (!nc_ncuserService.Instance.Get_IsExist_ByWhere(ShareMarking.Entity.nc_ncuser._.nc_code == o.nc_code))
                        {
                            #region 新增NC
                            ShareMarking.Entity.nc_ncuser nc = new ShareMarking.Entity.nc_ncuser()
                            {
                                id = o.id.ToString(),
                                nc_code = o.nc_code,
                                password = o.password,
                                name = o.name,
                                tel = o.tel,
                                email = o.email,//"新增接口正式",
                                state = o.state,
                                nc_nature = o.nc_nature,
                                entr_date = o.entr_date,
                                leave_date = o.leave_date,
                                ncl_code = o.ncl_code,
                                ncl_name = o.ncl_name,
                                ncl_tel = o.ncl_tel,
                                isneedupdate = true
                            };
                            nc_ncuserService.Instance.Add_Entity(nc);

                            ComLib.LogLib.Log4NetBase.Log("2-1、=======新增一条NC====NCCODE:" + o.nc_code + "=======NC状态======" + o.state);

                            #endregion
                        }
                        else
                        {
                            #region 更新NC
                            var nc = nc_ncuserService.Instance.Get_SingleEntity_byWhere(
                                    ShareMarking.Entity.nc_ncuser._.nc_code == o.nc_code);
                            var oldstate = nc.state;
                            if (oldstate != o.state)//必须在前，在后面会覆盖值
                            {
                                nc.isneedupdate = true;
                            }
                            else
                            {
                                nc.isneedupdate = false;
                            }
                            nc.name = o.name;
                            nc.tel = o.tel;
                            nc.email = o.email;//"修改接口正式";
                            nc.state = o.state;
                            nc.nc_nature = o.nc_nature;
                            nc.entr_date = o.entr_date;
                            nc.leave_date = o.leave_date;
                            nc.ncl_code = o.ncl_code;
                            nc.ncl_name = o.ncl_name;
                            nc.ncl_tel = o.ncl_tel;

                            nc_ncuserService.Instance.Update_Entity(nc);

                            ComLib.LogLib.Log4NetBase.Log("2-2、=========更新NC数据====NCCODE:" + o.nc_code +
                                "====新的状态为:" + nc.state +
                                "====旧的状态为:" + oldstate +
                                "====是否需要更新:" + nc.isneedupdate);

                            #endregion
                        }
                        a++;
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        ComLib.LogLib.Log4NetBase.Log("2-3、====同步NC数据====错误=====" + ex.Message + ex.StackTrace);
                    }
                });
                currentpage += 1;
                nextpage += 1;
                ComLib.LogLib.Log4NetBase.Log("2、====同步NC数据====处理第++" + i + "++页数据结束");
            }
            ComLib.LogLib.Log4NetBase.Log("2、====同步NC数据========结束====共获取到++" + a + "++条数据");
            #endregion
        }

        //private static void Sync(NC_Sync ncsync)
        //{
        //    #region 正常请求NC平台数据处理处理
        //    //先获取所有NC数量
        //    var count = ncsync.GetNCCount();
        //    ComLib.LogLib.Log4NetBase.Log("1、====同步NC数据====获取NC数量为：：" + count);

        //    var pagesize = 50;
        //    var currentpage = 1;
        //    var nextpage = 1;
        //    int a = 0;
        //    var pagecout = (int)(count / pagesize);
        //    for (int i = 0; i <= pagecout; i++)
        //    {
        //        //获取一页数据
        //        var resultentity = ncsync.GetNC(currentpage, nextpage, pagesize, count);
        //        ComLib.LogLib.Log4NetBase.Log("2、====同步NC数据====获取第++" + i + "++页数据：：state:"
        //                    + resultentity.state + ":::msg:::" + resultentity.message);

        //        var enlit = resultentity.result.list;
        //        //string ReturnStr = "";
        //        enlit.ForEach(o =>
        //        {
        //            try
        //            {
        //                #region 处理一条数据
        //                if (!nc_ncuserService.Instance.Get_IsExist_ByWhere(ShareMarking.Entity.nc_ncuser._.nc_code == o.nc_code))
        //                {
        //                    #region 新增NC
        //                    ShareMarking.Entity.nc_ncuser nc = new ShareMarking.Entity.nc_ncuser()
        //                    {
        //                        id = o.id.ToString(),
        //                        nc_code = o.nc_code,
        //                        password = o.password,
        //                        name = o.name,
        //                        tel = o.tel,
        //                        email = o.email,//"新增接口正式",
        //                        state = o.state,
        //                        nc_nature = o.nc_nature,
        //                        entr_date = o.entr_date,
        //                        leave_date = o.leave_date,
        //                        ncl_code = o.ncl_code,
        //                        ncl_name = o.ncl_name,
        //                        ncl_tel = o.ncl_tel,
        //                        isneedupdate = true
        //                    };
        //                    nc_ncuserService.Instance.Add_Entity(nc);

        //                    ComLib.LogLib.Log4NetBase.Log("2-1、=======新增一条NC====NCCODE:" + o.nc_code + "=======NC状态======" + o.state);

        //                    #endregion
        //                }
        //                else
        //                {
        //                    #region 更新NC
        //                    var nc = nc_ncuserService.Instance.Get_SingleEntity_byWhere(
        //                            ShareMarking.Entity.nc_ncuser._.nc_code == o.nc_code);
        //                    var oldstate = nc.state;

        //                    if (o.state == "活跃员工")
        //                    {
        //                        nc.isneedupdate = true;
        //                        //if (oldstate != o.state)//必须在前，在后面会覆盖值
        //                        //{
        //                        //    nc.isneedupdate = true;
        //                        //}
        //                        //else
        //                        //{
        //                        //    nc.isneedupdate = false;
        //                        //}
        //                        nc.name = o.name;
        //                        nc.tel = o.tel;
        //                        nc.email = o.email;//"修改接口正式";
        //                        nc.state = o.state;
        //                        nc.nc_nature = o.nc_nature;
        //                        nc.entr_date = o.entr_date;
        //                        nc.leave_date = o.leave_date;
        //                        nc.ncl_code = o.ncl_code;
        //                        nc.ncl_name = o.ncl_name;
        //                        nc.ncl_tel = o.ncl_tel;

        //                        nc_ncuserService.Instance.Update_Entity(nc);
        //                    }

        //                    ComLib.LogLib.Log4NetBase.Log("2-2、=========更新NC数据====NCCODE:" + o.nc_code +
        //                        "====新的状态为:" + nc.state +
        //                        "====旧的状态为:" + oldstate +
        //                        "====是否需要更新:" + nc.isneedupdate);

        //                    #endregion
        //                }
        //                a++;
        //                #endregion

        //                //#region 获取所有NC_CODE
        //                //ReturnStr += o.nc_code + ",";
        //                //#endregion
        //            }
        //            catch (Exception ex)
        //            {
        //                ComLib.LogLib.Log4NetBase.Log("2-3、====同步NC数据====错误=====" + ex.Message + ex.StackTrace);
        //            }
        //        });
        //        //ComLib.LogLib.Log4NetBase.Log("NC_CODE:in(" + DelLastComma(ReturnStr) + ")");
        //        currentpage += 1;
        //        nextpage += 1;
        //        ComLib.LogLib.Log4NetBase.Log("2、====同步NC数据====处理第++" + i + "++页数据结束");
        //    }
        //    ComLib.LogLib.Log4NetBase.Log("2、====同步NC数据========结束====共获取到++" + a + "++条数据");
        //    #endregion
        //}

        public static string DelLastComma(string str)
        {
            return str.Substring(0, str.LastIndexOf(","));
        }
    }
}
